<!--
 * @Descripttion:回款弹窗组件
-->
<template>
  <CustomDialog
    v-model:visible="visible"
    @close="handleCancel"
    top="3vh"
    curentClass="return-dialog"
  >
    <div class="dialog-content">
      <div class="title">新增回款</div>
    </div>
    <div class="dialog-header-box" v-if="orderDetailInfo">
      <div class="account-box">
        <span class="account-title">账户名称：{{ selectedTableRowOrderData.org?.name }}</span>
      </div>
      <div class="return-box">
        <span class="return-title">回款人</span>
        <el-input type="text" class="return-input" v-model.trim="returnName" />
      </div>
      <div class="onAccount-money-box">
        <span class="onAccount-title">挂账金额：{{ orderDetailInfo?.orderInfo?.pay_money }}</span>
      </div>
    </div>

    <div class="dialog-content-box" v-if="orderDetailInfo">
      <!-- 左：回款账单（可绑定/解绑） -->
      <div class="left-box">
        <div class="left-title">回款账单</div>
        <div class="left-all-box">
          <div class="left-loop-box">
            <div
              class="left-list-item"
              v-for="(item, index) in orderDetailInfo.logList"
              :key="index"
              @click.stop="handleBindAction(item)"
            >
              <span class="list-name">{{ item.log_id }}</span>
              <span class="list-price">
                ￥{{ item.money }}
                <img
                  v-if="item.isChecked"
                  class="choose-img"
                  src="@/assets/images/home/xuanzhongzhuotai.png"
                  alt=""
                />
              </span>
            </div>
          </div>
          <div class="left-summary-box" v-if="orderDetailInfo.logList?.length">
            共{{ orderDetailInfo.logList.length }}条
          </div>
        </div>
      </div>

      <div class="line"></div>

      <!-- 中：客户支付方式 + 金额输入 + 数字键盘 -->
      <div class="center-box">
        <div class="center-title">客户支付方式</div>
        <div class="center-scroll-list">
          <div
            class="center-scroll-item"
            :class="{ 'scroll-item-active': selectActiveIndex === index }"
            v-for="(item, index) in rechargeTypeList"
            :key="index"
            @click="handleSelect(index, item)"
          >
            <img
              v-if="
                imageData[item.method + (item.method === 'on_account' ? item.others?.type : '')]
                  ?.image && selectActiveIndex !== index
              "
              class="image"
              :src="
                imageData[item.method + (item.method === 'on_account' ? item.others?.type : '')]
                  .image
              "
              alt=""
            />
            <img
              v-else-if="
                imageData[item.method + (item.method === 'on_account' ? item.others?.type : '')]
                  ?.activeImage
              "
              class="image"
              :src="
                imageData[item.method + (item.method === 'on_account' ? item.others?.type : '')]
                  .activeImage
              "
              alt=""
            />
            <img
              v-else
              class="image"
              :src="imageData.default.image"
              alt=""
            />
            <div class="desc" v-if="item.method === 'balance'">会员支付</div>
            <div class="desc" v-if="item.method === 'cash'">现金支付</div>
            <div class="desc" v-if="item.method === 'alipay'">支付宝</div>
            <div class="desc" v-if="item.method === 'wechat'">微信</div>
            <div class="desc" v-if="item.method === 'on_account' && item.others?.type === 1">
              企业挂账
            </div>
            <div class="desc" v-if="item.method === 'on_account' && item.others?.type === 2">
              个人挂账
            </div>
            <div  class="desc" v-else>
              {{ item.others?.name }}
            </div>
          </div>
          <div
            class="scroll-list-item-zhanwei"
            v-for="val in ['val1', 'val2', 'val3', 'val4']"
            :key="val"
          ></div>
        </div>
        <div class="form-box">
          <div class="form-item">
            <div class="dialog-input">
              <input
                class="input"
                v-model.trim="payMoney"
                type="text"
                placeholder="请输入客户支付的金额并确认"
              />
              <img
                class="image"
                src="@/assets/images/home/input-clear.png"
                alt=""
                @click="handleClearInput"
                v-if="payMoney"
              />
            </div>
          </div>
        </div>
        <NumberKeyboard
          v-model:keyword="payMoney"
          :loading="paying"
          @onInputKeyboard="onInputKeyboard"
          @onCancel="handleClearInput"
          @onConfirm="onConfirm"
        />
      </div>

      <div class="line"></div>

      <!-- 右：客户已付方式列表与总计、确认 -->
      <div class="right-box">
        <div class="right-title">回款账单</div>
        <div class="right-loop-box">
          <div
            class="right-list-item"
            v-for="(item, index) in payMethodList"
            :key="index"
            @click.stop="handleCancelOrderPay(item.pay_method)"
          >
            <div class="right-list-name-box">
              <img
                class="right-list-img"
                v-if="
                  imageData[item.pay_method + (item.pay_method === 'on_account' ? item.type : '')]
                    ?.image
                "
                :src="
                  imageData[item.pay_method + (item.pay_method === 'on_account' ? item.type : '')]
                    .image
                "
                alt=""
              />
              <img
                v-else
                class="right-list-img"
                :src="imageData.default.image"
                alt=""
              />
              <div class="right-list-name" v-if="item.pay_method === 'balance'">会员支付</div>
              <div class="right-list-name" v-if="item.pay_method === 'cash'">现金支付</div>
              <div
                class="right-list-name"
                v-if="item.pay_method === 'on_account' && item.type === 1"
              >
                企业挂账
              </div>
              <div
                class="right-list-name"
                v-if="item.pay_method === 'on_account' && item.type === 2"
              >
                个人挂账
              </div>
              <div class="right-list-name" v-else>
                {{ item.name }}
              </div>
            </div>
            <div class="price-box">
              ￥{{ item.money }}
              <img class="shanchu-icon" src="@/assets/images/bill/shanchu-x.png" alt="" />
            </div>
          </div>
        </div>
        <div class="right-summary-box">
          <div class="summary-left-text"></div>
          <div class="summary-right-text">
            挂账金额￥{{ orderDetailInfo?.payInfo?.money }}，剩余回款：￥{{ notReceivedAmount }}
          </div>
        </div>
        <div class="btn-group">
          <span class="cancel" @click="handleCancel">取消</span>
          <el-button class="submit" type="primary" :loading="submitLoading" @click="handleSubmit"
            >确定回款</el-button
          >
        </div>
      </div>
    </div>

    <!-- 选择挂账账户弹窗 -->
    <SelectPayCreditDialog
      :isShowDialog="showSelectPayCreditDialog"
      :payCreditType="payCreditType"
      @update:isShowDialog="val => (showSelectPayCreditDialog = val)"
      @confirm="onSelectPayCredit"
    />
  </CustomDialog>
  <!-- 扫码隐藏输入 -->
  <input class="scanInput" ref="scanInput" type="text" v-model.trim="scannerBackValue" />
  <!-- 扫码枪弹框 -->
  <ScannerDialog
    v-model:visible="showScannerDialog"
    @onScan="onScannerScan"
    @onCancel="onScannerCancel"
  />
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import CustomDialog from '@/components/CustomDialog/Index.vue'
import NumberKeyboard from '@/components/NumberKeyboard/Index.vue'
import SelectPayCreditDialog from '@/components/SelectPayCreditDialog/Index.vue'
import ScannerDialog from '@/components/ScannerDialog/index.vue'
import { dealAssignDataFunction } from '@/utils/toolsValidate'
import { paymentList, cashierOrderPay, cashierTradeQuery, ashierTradeConfirmPay } from '@/api/pay'
import {
  creditRepaymentOrderInfo,
  creditOrderBindLog,
  orderUnBindLog,
  payMoneyOrderCancel
} from '@/api/statistics'
import MessageTips from '@/components/messageTips'
import { bus } from '@/utils/bus'

// 静态资源（兼容 Vite 环境，替代 require）
import imgBalance from '@/assets/images/home/huiyuanzhifu.png'
import imgBalanceActive from '@/assets/images/home/huiyuanzhifu-active.png'
import imgCash from '@/assets/images/home/xianjin-icon.png'
import imgQiYe from '@/assets/images/home/qiyeguazhang.png'
import imgGeRen from '@/assets/images/home/gerenguazhang.png'
import imgJifen from '@/assets/images/home/jifendikou.png'
import imgAlipay from '@/assets/images/home/zhifubazhifu.png'
import imgWechat from '@/assets/images/home/wechat.png'
import imgDefault from '@/assets/images/home/xushou.png'

interface Props {
  returnVisible: boolean
  selectedLogId: string
  selectedTableRowOrderData: any
}
const props = withDefaults(defineProps<Props>(), {
  returnVisible: false,
  selectedLogId: '',
  selectedTableRowOrderData: {}
})
const emit = defineEmits(['update:returnVisible', 'onConfirmSuccess'])

const visible = computed({
  get: () => props.returnVisible,
  set: v => emit('update:returnVisible', v)
})

// 状态
const returnName = ref('')
const payMoney = ref('')
const selectActiveIndex = ref(-1)
const rechargeTypeList = ref<any[]>([])
const selectActivePayMethod = ref<any>({})
const orderDetailInfo = ref<any>(null)
const payMethodList = ref<any[]>([])
const showSelectPayCreditDialog = ref(false)
const payCreditType = ref(1) // 1企业 2个人
const selectPayCreditId = ref<number | null>(null)
const creditLevelType = ref<number | null>(null) // 0主账户(个人) 1子账户(企业)
const scannerBackValue = ref('')
const scanInput = ref<HTMLInputElement | null>(null)
const isFlag = ref(false)
const showScannerDialog = ref(false)
const paying = ref(false)
const submitLoading = ref(false)

const notReceivedAmount = computed(() => {
  const total = Number(orderDetailInfo.value?.payInfo?.money || 0)
  const paid = Number(orderDetailInfo.value?.payInfo?.pay_money || 0)
  return (total - paid).toFixed(2)
})

// 支付方式图标（与旧项目保持）
const imageData: any = {
  balance: { image: imgBalance, activeImage: imgBalanceActive },
  cash: { image: imgCash, activeImage: imgCash },
  on_account1: { image: imgQiYe, activeImage: imgQiYe },
  on_account2: { image: imgGeRen, activeImage: imgGeRen },
  integripay: { image: imgJifen, activeImage: imgJifen },
  alipay: { image: imgAlipay, activeImage: imgAlipay },
  wechat: { image: imgWechat, activeImage: imgWechat },
  default: { image: imgDefault, activeImage: imgDefault }
}

watch(visible, async val => {
  if (val && props.selectedLogId) {
    resetForm()
    await getCreditRepaymentOrderInfo()
    await getPaymentList()
  }
})

watch(scannerBackValue, async newVal => {
  if (newVal) {
    setTimeout(async () => {
      if (!isFlag.value) {
        await handleOrderPay()
        isFlag.value = true
      }
    }, 800)
  }
})

const resetForm = () => {
  returnName.value = ''
  payMoney.value = ''
  selectActiveIndex.value = -1
  selectActivePayMethod.value = {}
  showSelectPayCreditDialog.value = false
  selectPayCreditId.value = null
  creditLevelType.value = null
  scannerBackValue.value = ''
  isFlag.value = false
  console.log('挂账了-2');
  
  bus.on('guazhang-list-refresh', handleGuazhangListRefresh)
}

const handleGuazhangListRefresh = () => {
  if (visible.value) {
    getCreditRepaymentOrderInfo()
  }
}

onUnmounted(() => {
  bus.off('guazhang-list-refresh', handleGuazhangListRefresh)
})
// 获取回款订单信息
const getCreditRepaymentOrderInfo = async () => {
  const datas: any = { user_name: returnName.value, log_id: props.selectedLogId }
  const res: any = await creditRepaymentOrderInfo(datas)
  if (res?.status === 200) {
    orderDetailInfo.value = dealAssignDataFunction(null, res?.data)
    payMethodList.value = dealAssignDataFunction([], res?.data?.payList)
    returnName.value = dealAssignDataFunction('', orderDetailInfo.value?.orderInfo?.user_name)
  }
}

// 获取支付方式
const getPaymentList = async () => {
  const res: any = await paymentList({ balance: 0 })
  if (res?.status === 200) {
    rechargeTypeList.value = dealAssignDataFunction([], res?.data)
  }
}

const handleSelect = (index: number, item: any) => {
  selectActiveIndex.value = index
  selectActivePayMethod.value = item
  if (item.method === 'on_account' && item.others?.type === 1) {
    payCreditType.value = 1
    showSelectPayCreditDialog.value = true
    return
  }
  if (item.method === 'on_account' && item.others?.type === 2) {
    payCreditType.value = 2
    showSelectPayCreditDialog.value = true
  }
}

const onSelectPayCredit = (datas: any) => {
  selectPayCreditId.value = datas.selectPayCreditId
  creditLevelType.value = datas.payType
}

const handleClearInput = () => {
  payMoney.value = ''
}
const onInputKeyboard = (val: string) => {
  payMoney.value = val
}

const requireScanIfNeeded = async (): Promise<boolean> => {
  if (['wechat', 'alipay'].includes(selectActivePayMethod.value.method)) {
    if (!scannerBackValue.value) {
      showScannerDialog.value = true
      return false
    }
  }
  return true
}

const handleOrderPay = async () => {
  paying.value = true
  const datas: any = {
    order_id: orderDetailInfo.value.orderInfo.id,
    method: selectActivePayMethod.value.method,
    extra: { order_type: 20, money: payMoney.value }
  }
  if (selectActivePayMethod.value.method === 'on_account') {
    datas.extra.credit_id = selectPayCreditId.value
    datas.extra.type = creditLevelType.value
  }
  if (['wechat', 'alipay'].includes(selectActivePayMethod.value.method)) {
    datas.extra.pay_type = 'faceToFace'
    datas.extra.auth_code = scannerBackValue.value
  } 
  if (selectActivePayMethod.value.method === 'virtual') {
    datas.extra.name = selectActivePayMethod.value.others?.name
  }
  const res: any = await cashierOrderPay(datas).catch(() => null)
  if (res?.status === 200) {
    if (['wechat', 'alipay'].includes(selectActivePayMethod.value.method)) {
      const outTradeNo = res?.data?.payment?.out_trade_no
      if (outTradeNo) await fetchCashierTradeQuery(outTradeNo)
    } else {
      handleClearInput()
      ElMessage.success('操作成功')
      await getCreditRepaymentOrderInfo()
    }
  }
  if (['wechat', 'alipay'].includes(selectActivePayMethod.value.method)) {
    isFlag.value = false
    scannerBackValue.value = ''
  }
  paying.value = false
}

const fetchCashierTradeQuery = async (outNo: string) => {
  const res: any = await cashierTradeQuery({
    out_trade_no: outNo,
    method: selectActivePayMethod.value.method
  })
  if (res?.status === 200) {
    if (res?.data?.isPay) {
      handleClearInput()
      await getCreditRepaymentOrderInfo()
      ElMessage.success(res.message || '支付成功')
    } else {
      await ElMessageBox.confirm('未检测到成功支付，是否继续扫码？', '提示', {
        type: 'warning'
      }).catch(() => {})
      await nextTick()
      scanInput.value?.focus?.()
    }
  }
}

const handleCancelOrderPay = async (payMethod: string) => {
  const datas = {
    order_id: orderDetailInfo.value.orderInfo.id,
    method: payMethod,
    extra: { order_type: 20 }
  }
  const res: any = await payMoneyOrderCancel(datas).catch(() => null)
  if (res?.status === 200) {
    ElMessage.success('取消支付成功')
    await getCreditRepaymentOrderInfo()
  }
}

// 绑定/解绑挂账日志
const handleBindAction = async (item: any) => {
  // 同步金额：选中加、取消减
  const delta = Number(item.money || 0)
  if (item.isChecked) {
    const pramas = { log_id: item.log_id }
    const res: any = await orderUnBindLog(pramas)
    if (res?.status === 200) {
      ElMessage.success('解绑成功')
      // 取消勾选：从输入框减
      payMoney.value = (Number(payMoney.value || 0) - delta).toFixed(2)
      await getCreditRepaymentOrderInfo()
    }
    return
  }
  const datas = { log_id: item.log_id, order_id: orderDetailInfo.value.orderInfo.id }
  const res: any = await creditOrderBindLog(datas)
  if (res?.status === 200) {
    ElMessage.success('绑定成功')
    // 勾选：把挂账金额加到输入框
    payMoney.value = (Number(payMoney.value || 0) + delta).toFixed(2)
    await getCreditRepaymentOrderInfo()
  }
}

const onConfirm = async () => {
  if (selectActiveIndex.value === -1) {
    ElMessage.warning('请先选择支付方式')
    return
  }
  if (!returnName.value) {
    ElMessage.warning('请输入回款人姓名')
    return
  }
  if (!payMoney.value) {
    ElMessage.warning('请输入金额')
    return
  }
  const total = Number(orderDetailInfo.value?.payInfo?.money || 0)
  if (parseFloat(payMoney.value) > total) {
    ElMessage.warning('输入的金额不能大于总挂账金额')
    return
  }
  const canPay = await requireScanIfNeeded()
  if (canPay) {
    await handleOrderPay()
  }
}

const handleSubmit = async () => {
  if (submitLoading.value) return
  const messageTipsInstance = await MessageTips.message(
    {
      title: '回款',
      content: '确认完成回款？',
      isOnCancel: true,
      onCancelText: '取消',
      onSumbitText: '确定'
    },
    async () => {
      try {
        submitLoading.value = true
        messageTipsInstance.setLoading(true)
        const datas = { order_id: orderDetailInfo.value.orderInfo.id, extra: { order_type: 20 } }
        const res: any = await ashierTradeConfirmPay(datas)
        if (res?.status === 200) {
          ElMessage.success('回款成功')
          emit('update:returnVisible', false)
          emit('onConfirmSuccess')
        }
      } catch (e) {
        // ignore
      } finally {
        submitLoading.value = false
        messageTipsInstance.close()
      }
    }
  )
}

const handleCancel = () => {
  emit('update:returnVisible', false)
}

// 扫描弹框回调
const onScannerScan = async (val: string) => {
  scannerBackValue.value = val
  showScannerDialog.value = false
  await handleOrderPay()
}
const onScannerCancel = () => {
  showScannerDialog.value = false
}
</script>

<style lang="scss" scoped>
.scanInput {
  position: fixed;
  z-index: -1;
  top: -9999999px;
  left: -9999999px;
  background: transparent !important;
  padding: 0 !important;
  outline: none !important;
  border: none !important;
}
.dialog-content {
  .title {
    font-size: 20px;
    font-family:
      PingFang SC,
      PingFang SC-Bold;
    font-weight: 700;
    text-align: left;
    color: #000000;
    margin-bottom: 10px;
  }
}
.dialog-header-box {
  display: flex;
  align-items: center;
  margin-top: 20px;
  .account-box {
    display: flex;
    margin-right: 60px;
    align-items: center;
    .account-title {
      font-size: 18px;
      color: #333333;
      margin-right: 20px;
    }
  }
  .return-box {
    display: flex;
    margin-right: 60px;
    align-items: center;
    .return-title {
      font-size: 18px;
      color: #333333;
      margin-right: 20px;
    }
    .return-input {
      width: 224px;
      height: 48px;
      background: #ffffff;
      border-radius: 12px;
    }
  }
  .onAccount-money-box {
    display: flex;
    align-items: center;
    margin-right: 60px;
    .onAccount-title {
      font-size: 18px;
      color: #333333;
      margin-right: 20px;
    }
  }
}
.dialog-content-box {
  display: flex;
  margin-top: 40px;
  .left-box {
    width: 409px;
    .left-title {
      font-size: 18px;
      font-weight: 700;
      color: #333333;
      margin-bottom: 20px;
    }
    .left-all-box {
      height: 652px;
      width: 100%;
      background: #f4f4f4;
      border-radius: 12px;
      display: flex;
      padding: 21px 24px 21px;
      box-sizing: border-box;
      flex-direction: column;
      justify-content: space-between;
      .left-loop-box {
        display: flex;
        flex-direction: column;
        box-sizing: border-box;
        height: 630px;
        overflow-y: auto;
        .left-list-item {
          width: 344px;
          background: #ffffff;
          border-radius: 12px;
          display: flex;
          margin-bottom: 30px;
          padding: 15px 30px;
          box-sizing: border-box;
          align-items: center;
          justify-content: space-between;
          cursor: pointer;
          .list-price {
            display: flex;
            align-items: center;
            .choose-img {
              width: 15px;
              height: 15px;
              flex-shrink: 0;
              margin-left: 10px;
            }
          }
        }
      }
      .left-summary-box {
        margin-top: 10px;
        display: flex;
        align-items: flex-end;
        font-size: 16px;
        color: #333333;
      }
    }
  }
  .line {
    width: 1px;
    height: 718px;
    background: #e2e2e2;
    margin-left: 30px;
  }
  .center-box {
    width: 516px;
    margin-left: 30px;
    .center-title {
      font-size: 18px;
      font-weight: 700;
      color: #333333;
      padding-left: 16px;
    }
    .center-scroll-list {
      width: 516px;
      height: 248px;
      border: 1px solid #e2e2e2;
      border-radius: 12px;
      overflow-y: auto;
      display: flex;
      align-items: center;
      justify-content: space-between;
      flex-wrap: wrap;
      margin-top: 20px;
      box-sizing: border-box;
      padding: 0 24px 20px 24px;
      .center-scroll-item {
        box-sizing: border-box;
        padding-left: 6px;
        width: 140px;
        height: 56px;
        background: #f4f4f4;
        border-radius: 12px;
        display: flex;
        align-items: center;
        cursor: pointer;
        margin-top: 20px;
        color: #333333;
        .image {
          flex-shrink: 0;
          width: 30px;
          height: 30px;
          margin-right: 10px;
        }
        .desc {
          font-size: 14px;
        }
      }
      .scroll-item-active {
        background: #7c0a03 !important;
        color: #fff !important;
      }
    }
    .scroll-list-item-zhanwei {
      width: 140px;
      overflow: hidden;
    }
    .form-box {
      margin-top: 40px;
      margin-bottom: 30px;
      .form-item {
        .dialog-input {
          width: 516px;
          height: 48px;
          background: #ffffff;
          border: 1px solid #d2d2d2;
          border-radius: 12px;
          box-sizing: border-box;
          padding: 0 20px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          .input {
            width: 400px;
            font-size: 14px;
            color: #333333;
            outline: none;
            border: none;
          }
          .image {
            flex-shrink: 0;
            width: 24px;
            height: 24px;
            cursor: pointer;
          }
        }
      }
    }
  }
  .right-box {
    width: 504px;
    margin-left: 30px;
    .right-title {
      font-size: 18px;
      font-weight: 700;
      color: #333333;
      margin-bottom: 20px;
    }
    .right-loop-box {
      width: 504px;
      height: 528px;
      background: #f4f4f4;
      border-radius: 12px;
      box-sizing: border-box;
      padding: 20px 24px 20px;
      overflow-y: auto;
      .right-list-item {
        width: 448px;
        height: 48px;
        background: #ffffff;
        border-radius: 12px;
        display: flex;
        align-items: center;
        margin-bottom: 20px;
        box-sizing: border-box;
        padding: 13px 20px 13px 16px;
        justify-content: space-between;
        cursor: pointer;
        .right-list-name-box {
          display: flex;
          align-items: center;
          .right-list-img {
            width: 30px;
            height: 30px;
            margin-right: 20px;
          }
          .right-list-name {
            font-size: 16px;
            color: #333333;
          }
        }
        .price-box {
          display: flex;
          align-items: center;
          font-size: 16px;
          color: #333333;
          .shanchu-icon {
            flex-shrink: 1;
            width: 20px;
            height: 20px;
            margin-left: 10px;
          }
        }
      }
    }
    .right-summary-box {
      display: flex;
      justify-content: space-between;
      margin-top: 30px;
      .summary-left-text {
        font-size: 16px;
        color: #333333;
      }
      .summary-right-text {
        font-size: 16px;
        color: #333333;
      }
    }
    .btn-group {
      margin-top: 30px;
      display: flex;
      justify-content: space-around;
      align-items: center;
      .cancel {
        width: 100px;
        height: 52px;
        background: #ffffff;
        border: 1px solid #333333;
        border-radius: 12px;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 18px;
        color: #333333;
        cursor: pointer;
      }
      .submit {
        width: 336px;
        height: 52px;
        background: #7c0a03;
        border-radius: 12px;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 18px;
        color: #ffffff;
        cursor: pointer;
      }
    }
  }
}
</style>
<style>
.return-dialog {
  max-height: unset !important;
}
</style>
